package com.lemo.smart.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet 助手类
 * Created by 罗选通 on 2017/12/25.
 */
public class ServletHelper {

  private static final Logger logger = LoggerFactory.getLogger(ServletHelper.class);

  private static final ThreadLocal<ServletHelper> SERVLET_HELPER_HOLDER = new ThreadLocal<ServletHelper>();

  private HttpServletRequest request;
  private HttpServletResponse response;

  private ServletHelper(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;
  }

  /**
   * 初始化
   */
  public static void init(HttpServletRequest request, HttpServletResponse response) {
    SERVLET_HELPER_HOLDER.set(new ServletHelper(request, response));
  }

  /**
   * 销毁
   */
  public static void destroy() {
    SERVLET_HELPER_HOLDER.remove();
  }

  /**
   * 获取request对象
   */
  public static HttpServletRequest getRequest() {
    return SERVLET_HELPER_HOLDER.get().request;
  }


  /**
   * 获取response对象
   */
  public static HttpServletResponse getResponse() {
    return SERVLET_HELPER_HOLDER.get().response;
  }

  /**
   * 获取session对象
   */
  public static HttpSession getSession() {
    return getRequest().getSession();
  }

  /**
   * 获取servletContext对象
   */
  public static ServletContext getServletContext() {
    return getRequest().getServletContext();
  }

  /**
   * 在request中放入属性值
   */
  public static void setRequestAttribute(String key, Object value) {
    getRequest().setAttribute(key, value);
  }

  public static <T> T getRequestAttribute(String key) {
    return (T) getRequest().getAttribute(key);
  }

  public static void removeRequestAttribute(String key){
    getRequest().removeAttribute(key);
  }

  public static void sendRedirect(String url){
    try {
      getResponse().sendRedirect(getRequest().getContextPath()+url);
    } catch (IOException e) {
      logger.error("redirect failure",e);
      e.printStackTrace();
    }
  }



}
